package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.PreferentialService;
import com.qingcheng.util.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService{

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private SkuService skuService;

    @Reference
    private CategoryService categoryService;

    @Autowired
    private PreferentialService preferentialService;

    @Override
    public List<Map<String, Object>> findCartList(String username) {
        System.out.println("从rides中获取用户名:"+username);
        List<Map<String,Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if (cartList == null){
            cartList = new ArrayList<>();
        }
        return cartList;
    }

    @Override
    public void addItem(String username, String skuId, Integer num) {
        List<Map<String, Object>> cartList = findCartList(username);

        boolean flag = false; //购物车没有商品
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");  //获取商品明细
            if (orderItem.getSkuId().equals(skuId)){ //相等说明存在该商品
                if (orderItem.getWeight()<=0){
                    cartList.remove(map);
                    flag=true;
                    break;
                }
                int weight = orderItem.getWeight()/orderItem.getNum();

                orderItem.setNum(orderItem.getNum()+num);
                orderItem.setMoney(orderItem.getPrice()*orderItem.getNum());
                orderItem.setWeight(weight*orderItem.getNum());

                if (orderItem.getNum()<=0){
                    cartList.remove(map);
                }

                flag=true;
                break;
            }
        }

        if (flag == false){   //没有商品则实例化map
            Sku sku = skuService.findById(skuId);
            if (sku == null){
                throw new RuntimeException("商品不存在");
            }
            if (!"1".equals(sku.getStatus())){
                throw new RuntimeException("商品已下架");
            }
            if (sku.getNum()<=0){
                throw new RuntimeException("商品已被卖光");
            }

            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(skuId);

            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(sku.getNum());
            orderItem.setImage(sku.getImage());
            orderItem.setPrice(sku.getPrice());
            orderItem.setName(sku.getName());
            orderItem.setMoney(sku.getPrice()*num);
            if (sku.getWeight() == null){
                sku.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight()*num);

            orderItem.setCategoryId3(sku.getCategoryId());
            Category category3 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGGORY).get(sku.getCategoryId());
            if (category3 == null){
                category3 = categoryService.findById(sku.getCategoryId());//获取3级ID
                redisTemplate.boundHashOps(CacheKey.CATEGGORY).put(sku.getCategoryId(),category3);
            }
            orderItem.setCategoryId2(category3.getParentId());//根据3级ID的父id存入2级ID


            Category category2 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGGORY).get(category3.getParentId());
            if (category2 == null){
                category2 = categoryService.findById(category3.getParentId());//获取2级ID
                redisTemplate.boundHashOps(CacheKey.CATEGGORY).put(category3.getParentId(),category2);
            }
            orderItem.setCategoryId1(category2.getParentId());//根据2级ID的父id存入1级ID

            Map map = new HashMap();
            map.put("item",orderItem);
            map.put("checked",true);
            cartList.add(map);

        }

        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
    }

    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        List<Map<String, Object>> cartList = findCartList(username);
        boolean isOk = false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (orderItem.getSkuId().equals(skuId)){
                map.put("checked",checked);
                isOk = true;
                break;
            }
        }
            if (isOk){
            redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
            }

        return isOk;
    }

    @Override
    public void deleteCheckedCart(String username) {
        //获得未选择的商品
        List<Map<String, Object>> cartList = findCartList(username).stream().filter( cart -> (boolean)cart.get("checked")==false )
                .collect(Collectors.toList());
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
    }

    @Override
    public int preferential(String username) {
        //获取选中的购物车
        List<OrderItem> orderItems = findCartList(username).stream()
                .filter( cart -> (boolean)cart.get("checked")==true)
                .map( cart -> (OrderItem)cart.get("item"))
                .collect(Collectors.toList());

        //按分类聚合统计每个分类的金额 group by    /分类  /金额
        Map<Integer, IntSummaryStatistics> cartMap = orderItems.stream()
                .collect(Collectors.groupingBy(OrderItem::getCategoryId3,
                        Collectors.summarizingInt(OrderItem::getMoney)
                ));

        int allPreMoeny =0;
        //循环结果，统计每个分类的优惠金额，并累加
        for (Integer categoryId : cartMap.keySet()) {
            int moeny = (int) cartMap.get(categoryId).getSum();
            int preMoeny = preferentialService.findPreMoenyByCategoryId(categoryId, moeny);
            System.out.println("分类:"+categoryId+" 消费金额:"+moeny+" 优惠金额："+preMoeny);
            allPreMoeny+= preMoeny;
        }

        return allPreMoeny;
    }


    //刷新新的购物车
    @Override
    public List<Map<String, Object>> findNewOrderItemList(String username) {
        //获取购物车
        List<Map<String, Object>> cartList = findCartList(username);
        //循环购物车
        for (Map<String, Object> cart : cartList) {
            OrderItem orderItem = (OrderItem) cart.get("item");
            Sku sku = skuService.findById(orderItem.getSkuId());
            orderItem.setPrice(sku.getPrice());  //存入价格
            orderItem.setMoney(sku.getPrice()*sku.getNum());
        }
        //保存到redis
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);

        return cartList;
    }
}
